package com.tocici.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.tocici.domain.Music;
import com.tocici.domain.User;
import com.tocici.domain.UserCateRelation;
import com.tocici.domain.vo.UserCateRelationVo;
import com.tocici.domain.vo.UserStatVo;
import com.tocici.mapper.MusicMapper;
import com.tocici.mapper.UserCateRelationMapper;
import com.tocici.mapper.UserMapper;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.tocici.domain.bo.UserBehaviorBo;
import com.tocici.domain.vo.UserBehaviorVo;
import com.tocici.domain.UserBehavior;
import com.tocici.mapper.UserBehaviorMapper;
import com.tocici.service.IUserBehaviorService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 用户行为Service业务层处理
 *
 * @author zeratul
 * @date 2025-03-02
 */
@RequiredArgsConstructor
@Service
public class UserBehaviorServiceImpl implements IUserBehaviorService {

    private final UserBehaviorMapper baseMapper;

    private final UserMapper userMapper;

    private final MusicMapper musicMapper;

    private final UserCateRelationMapper userCateRelationMapper;

    // 喜欢的权重
    private static final Double LIKE_POWER = 2.0;
//    命中类型的权重
    private static final Double CATE_POWER = 2.0;
//    播放量权重
    private static final Double PLAY_POWER = 0.10;


    /**
     * 查询用户行为
     *
     * @param behaviorId 主键
     * @return 用户行为
     */
    @Override
    public UserBehaviorVo queryById(Long behaviorId){
        return baseMapper.selectVoById(behaviorId);
    }

    /**
     * 分页查询用户行为列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户行为分页列表
     */
    @Override
    public TableDataInfo<UserBehaviorVo> queryPageList(UserBehaviorBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<UserBehavior> lqw = buildQueryWrapper(bo);
        Page<UserBehaviorVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户行为列表
     *
     * @param bo 查询条件
     * @return 用户行为列表
     */
    @Override
    public List<UserBehaviorVo> queryList(UserBehaviorBo bo) {
        LambdaQueryWrapper<UserBehavior> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<UserBehavior> buildQueryWrapper(UserBehaviorBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<UserBehavior> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(UserBehavior::getBehaviorId);
        lqw.eq(bo.getUserId() != null, UserBehavior::getUserId, bo.getUserId());
        lqw.eq(bo.getMusicId() != null, UserBehavior::getMusicId, bo.getMusicId());
        lqw.eq(bo.getPlayCount() != null, UserBehavior::getPlayCount, bo.getPlayCount());
        lqw.eq(bo.getIsLiked() != null, UserBehavior::getIsLiked, bo.getIsLiked());
        lqw.eq(bo.getInCateCollect() != null, UserBehavior::getInCateCollect, bo.getInCateCollect());
        lqw.eq(bo.getScore() != 0, UserBehavior::getScore, bo.getScore());
        lqw.eq(bo.getIsDeleted() != null, UserBehavior::getIsDeleted, bo.getIsDeleted());
        lqw.like(bo.getUsername() != null,UserBehavior::getUsername,bo.getUsername());
        lqw.like(bo.getTitle()!=null,UserBehavior::getTitle,bo.getUsername());
        lqw.eq(bo.getDuration() != null,UserBehavior::getDuration,bo.getDuration());
        return lqw;
    }

    /**
     * 新增用户行为
     *
     * @param bo 用户行为
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(UserBehaviorBo bo) {
        UserBehavior add = MapstructUtils.convert(bo, UserBehavior.class);
        LambdaQueryWrapper<UserBehavior> lqw = new LambdaQueryWrapper<>();
        lqw.eq(add.getUserId() != null,UserBehavior::getUserId,add.getUserId());
        lqw.eq(add.getMusicId() != null,UserBehavior::getMusicId,add.getMusicId());
        List<UserBehaviorVo> userBehaviorVos = baseMapper.selectVoList(lqw);
        if (userBehaviorVos.isEmpty()){
            UserBehavior returnResult = validEntityBeforeSave(add);
            Music music = musicMapper.selectById(add.getMusicId());
            LambdaQueryWrapper<UserCateRelation> uclqw = new LambdaQueryWrapper<>();
            uclqw.eq(UserCateRelation::getUserId,add.getUserId());
            List<UserCateRelationVo> userCateRelationVos = userCateRelationMapper.selectVoList(uclqw);
            if (userCateRelationVos.stream().map(UserCateRelationVo::getCateId).toList().contains(music.getCategoryId())){
                returnResult.setInCateCollect(1);
            }
            returnResult.setScore(returnResult.getIsLiked()*LIKE_POWER+returnResult.getInCateCollect()*CATE_POWER+ PLAY_POWER);
            boolean flag = baseMapper.insert(returnResult) > 0;
            if (flag) {
                bo.setBehaviorId(add.getBehaviorId());
            }
        }
        if (userBehaviorVos.size()>1){
            throw new ServiceException("有相同的记录");
        }
        if (userBehaviorVos.size() == 1){
            UserBehaviorVo userBehaviorVo = userBehaviorVos.get(0);
            UserBehaviorBo bean = BeanUtil.toBean(userBehaviorVo, UserBehaviorBo.class);
            bean.setScore(bean.getIsLiked()*LIKE_POWER+bean.getInCateCollect()*CATE_POWER+ (bean.getPlayCount()+1) * PLAY_POWER);
            bean.setPlayCount(bean.getPlayCount()+1);
            return updateByBo(bean);
        }
        return false;
    }

    /**
     * 修改用户行为
     *
     * @param bo 用户行为
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(UserBehaviorBo bo) {
        UserBehavior update = MapstructUtils.convert(bo, UserBehavior.class);
        UserBehavior returnResult = validEntityBeforeSave(update);
        update.setScore(update.getIsLiked()*LIKE_POWER+update.getInCateCollect()*CATE_POWER+ (update.getPlayCount()+1) * PLAY_POWER);
        return baseMapper.updateById(returnResult) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private UserBehavior validEntityBeforeSave(UserBehavior entity){
        Long userId = entity.getUserId();
        Long musicId = entity.getMusicId();
        User user = userMapper.selectById(userId);
        Music music = musicMapper.selectById(musicId);
        entity.setDuration(music.getDuration());
        entity.setTitle(music.getTitle());
        entity.setUsername(user.getUsername());
        return entity;


    }

    /**
     * 校验并批量删除用户行为信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<UserStatVo> getDurationStat() {
        List<UserStatVo> userStatVos = this.baseMapper.getDurationStat();
        return userStatVos;
    }
}
